package com.lagou.homework.controller;

import com.lagou.homework.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    UserService userService;

    /*
        注册接口 true 成功 false 失败
     */
    @PostMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable("email")String email,@PathVariable("password")String password,@PathVariable("code")String code){
        return userService.register(email,password,code);
    }

    /*
        判断是否已注册
     */
    @PostMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email")String email){
        return userService.isRegistered(email);
    }

    /*
        登录接口
     */
    @PostMapping("/login/{email}/{password}")
    public String login(@PathVariable("email")String email, @PathVariable("password")String password, HttpServletResponse response){
        String token = userService.login(email, password);
        if("用户名或密码错误".equals(token)){
            return "用户名或密码错误";
        }else{
            // 将 token 存入 cookie
            Cookie cookie = new Cookie("token",token);
            cookie.setMaxAge(7 * 24 * 60 * 60);// 设置存在一周
            cookie.setPath("/");//设置作用域
            response.addCookie(cookie);
            return email;
        }
    }

    /*
        根据token 获取邮箱地址
     */
    @PostMapping("/info/{token}")
    public String info(@PathVariable("token")String token){
        return userService.info(token);
    }
}

